// =============================================================
// scatter-gather model using Coord
// ---------------------------------------
// Author : Woo-Hyun Kim
// Email : woorung@icu.ac.kr or woorung@nhncorp.com
// Date : Oct. 29, 2008
// =============================================================
#include <iostream>

#include "md5/CMD5.h"
#include "discovery/Coord.h"

void randomize(int seed)
{
	srand(seed);
}

string &simple_hash(char *key, string &hashkey)
{
        CMD5 md5;
        unsigned char digest[32];
        md5.GetMD5Message(key, digest);

        char tmp[256];
        hashkey = "";
        for(int i=0;i<16;i++) {
                sprintf(tmp, "%02x",digest[i]);
                hashkey += tmp;
        }

        return hashkey;
}

pair<string,string> &get_kv(pair<string,string> &kv)
{
	int random_key = rand();

	char dd[100];
	sprintf(dd, "%d", random_key);
	kv.first = dd;
	kv.second = "";
	
	char data[100];
	for(int i=0;i<10;i++) {
		sprintf(data, "%s%d", (char *)kv.first.c_str(), i);
		string gen_value = "";
		gen_value = simple_hash(data, gen_value);

		kv.second += gen_value;
	}

	return kv;
}

int main(int argc, char **argv)
{
	int data_size = 10000;

	randomize(time(NULL));

	vector<pid_t> pid;

	for(int i=0;i<1;i++) {
		pid.push_back(fork());

		if(pid[i]==0) { // gather
			Coord gather("myspaces");
			gather.autoclean(false);

			for(int i=0;gather.size()>0;i++) {
				pair<string,string> keyval;
				keyval.first = "";

				gather.take(keyval);

				cout << "[" << i << "]" << keyval.first << "=" << keyval.second << endl;
			}

			exit(1);
		}
	}

	// scatter
	Coord scatter("myspaces");
	scatter.autoclean(false);

	pair<string,string> keyval;

	for(int i=0;i<data_size;i++) {
		keyval = get_kv(keyval);

		scatter.write(keyval);
	}

	int status; 
	pid_t wpid = waitpid(pid[0], &status, 0);

        return 1;
}
